<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>{{ $t('route.coupon') }}</h2>
        </template>
        <template v-slot:after>
          <el-button class="filter-item" size="medium" style="margin-left: 10px;" type="primary" icon="el-icon-edit" :disabled="!checkPermission('coupon-add')" @click="addOrEidt('add',0)">{{ $t('button.add') }}</el-button>
        </template>
      </PageTitle>
      <!-- 搜索筛选 -->
      <el-row :gutter="20" style="margin-top:20px">
        <el-col :span="4">
          <el-input v-model="query.name" type="text" :placeholder="$t('table.ForeignLanguageName')" />
        </el-col>
        <el-col :span="3">
          <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('button.search') }}</el-button>
        </el-col>
      </el-row>
      <!-- 数据表 -->
      <el-table v-loading="downloadLoading" border :data="list" max-height="650px" style="margin-top: 20px;">
        <el-table-column label="ID" prop="id" sortable="custom" width="60" />
        <el-table-column prop="type" label="类型">
          <template slot-scope="{row}">
            {{ row.type | shopType }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.ForeignLanguageName')" prop="name" />
        <el-table-column label="优惠金额" prop="money" />
        <el-table-column label="库存" prop="stock" />
        <el-table-column :label="$t('table.state')" prop="status" width="120">
          <template slot-scope="{row}">
            <el-tag :type="row.status|statusFilter">
              {{ row.status|formStatusData }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.creationTime')" prop="created_at">
          <template slot-scope="{row}">
            {{ row.createtime|timeStanp }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" width="220" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-edit" type="primary" size="mini" :disabled="!checkPermission('coupon-edit')" @click="addOrEidt('edit',row)">{{ $t('button.edit') }}</el-button>

            <el-button icon="el-icon-delete" type="dang er" size="mini" :disabled="!checkPermission('coupon-del')" @click="delData(row.id)">{{ $t('button.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" align="middle" style="margin-top:20px">
        <el-pagination background layout="total,prev,pager,next" :total="count" :page-size="query.limit" :current-page="query.page" @current-change="changPage" />
      </el-row>
    </div>
    <!-- 添加 -->
    <el-dialog :title="dialogTitle" :visible="showDialog" top="3%" @opened="openDialog" @close="btnCanle">
      <div class="shopOrder-dialog">
        <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="150px">
          <el-form-item label="类型" prop="type">
            <el-select v-model.number="formData.type" :placeholder="$t('table.selectThe')+'类型'">
              <el-option v-for="(item,index) in groupType" :key="index" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.ForeignLanguageName')" prop="name">
            <el-input v-model="formData.name" :placeholder="$t('table.enterThe')+' '+$t('table.ForeignLanguageName')" style="width:50%" />
          </el-form-item>
          <el-form-item label="有效期">
            <el-radio v-model.number="formData.yxqtype" :label="1">固定时间范围</el-radio>
            <el-radio v-model.number="formData.yxqtype" :label="2">领取后时长</el-radio>
          </el-form-item>
          <el-form-item v-if="formData.yxqtype===2" label="领取后时长">
            <el-input v-model.number="formData.yxqdate" style="width:10%" />
            <label class="margin-left-10">天内有效</label>
          </el-form-item>
          <el-form-item v-if="formData.yxqtype===1" label="有效期时间">
            <el-date-picker
              v-model.number="formData.yxqstart_time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              style="margin-right: 10px;width:35%"
            />-
            <el-date-picker
              v-model.number="formData.yxqend_time"
              type="datetime"
              placeholder="选择日期时间"
              value-format="timestamp"
              style="margin-left: 10px;width:35%"
            />
          </el-form-item>
          <el-form-item label="抵扣金额">
            <el-input v-model.number="formData.money" :placeholder="$t('table.enterThe')+'抵扣金额'" style="width:25%" />
          </el-form-item>
          <el-form-item label="最低消费金额">
            <el-input v-model.number="formData.minprice" :placeholder="$t('table.enterThe')+'最低消费金额'" style="width:25%" />
          </el-form-item>
          <el-form-item label="库存">
            <el-input v-model.number="formData.stock" :placeholder="$t('table.enterThe')+'库存'" style="width:25%" />
          </el-form-item>
          <el-form-item label="每人可领数量">
            <el-input v-model.number="formData.perlimit" :placeholder="$t('table.enterThe')+'最低消费金额'" style="width:25%" />
          </el-form-item>
          <el-form-item label="是否可赠送">
            <el-radio v-model.number="formData.isgive" :label="0">否</el-radio>
            <el-radio v-model.number="formData.isgive" :label="1">是</el-radio>
          </el-form-item>
          <el-form-item label="是否有领取条件">
            <el-radio v-model.number="formData.tolist" :label="0">无</el-radio>
            <el-radio v-model.number="formData.tolist" :label="1">有</el-radio>
          </el-form-item>
          <el-form-item v-if="formData.tolist===1" label="所需金额">
            <el-input v-model.number="formData.price" style="width:25%" />
          </el-form-item>
          <el-form-item v-if="formData.tolist===1" label="所需积分">
            <el-input v-model.number="formData.score" style="width:25%" />
          </el-form-item>
          <el-form-item :label="$t('table.showtj')">
            <el-checkbox-group v-model="checkList">
              <el-checkbox :label="-1">所有人</el-checkbox>
              <el-checkbox v-for="(item,index) in listLevel" :key="index" :label="item.id">{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="领取等级">
            <el-checkbox-group v-model="gettjList">
              <el-checkbox :label="-1">所有人</el-checkbox>
              <el-checkbox v-for="(item,index) in listLevel" :key="index" :label="item.id">{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="适用范围">
            <el-radio v-model.number="formData.fwtype" :label="0">全场通用</el-radio>
            <el-radio v-model.number="formData.fwtype" :label="1">指定类目</el-radio>
            <el-radio v-model.number="formData.fwtype" :label="2">指定服务商品</el-radio>
          </el-form-item>
          <el-form-item v-if="formData.fwtype===1" label="指定类目">
            <div>
              <table class="ljm-table" cellspacing="0" cellpadding="0">
                <thead>
                  <tr>
                    <th>分类ID</th>
                    <th>分类名称</th>
                    <th>{{ $t('table.actions') }}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item,index) in cateListObj" :key="index">
                    <td>{{ item.id }}</td>
                    <td>{{ item.name }}</td>
                    <td>
                      <el-button size="mini" @click="removeFreightArr('cate',index)">{{ $t('button.delete') }}</el-button>
                    </td>
                  </tr>
                  <tr>
                    <td colspan="3">
                      <el-button type="primary" size="mini" plain @click="openFreight('cate')">{{ $t('button.add') }}</el-button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </el-form-item>
          <el-form-item v-if="formData.fwtype===2" label="指定商品">
            <div>
              <table class="ljm-table" cellspacing="0" cellpadding="0">
                <thead>
                  <tr>
                    <th>商品ID</th>
                    <th>商品名称</th>
                    <th>{{ $t('table.actions') }}</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item,index) in shopList" :key="index">
                    <td>{{ item.id }}</td>
                    <td>{{ item.name }}</td>
                    <td>
                      <el-button size="mini" @click="removeFreightArr('shop',index)">{{ $t('button.delete') }}</el-button>
                    </td>
                  </tr>
                  <tr>
                    <td colspan="3">
                      <el-button type="primary" size="mini" plain @click="openFreight('shop')">{{ $t('button.add') }}</el-button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </el-form-item>
          <el-form-item :label="$t('table.state')" prop="status">
            <el-select v-model.number="formData.status" :placeholder="$t('table.selectThe')+' '+$t('table.state')">
              <el-option v-for="(item,index) in statusData" :key="index" :label="item.value" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="使用说明">
            <el-input v-model="formData.usetips" type="textarea" :rows="3" :placeholder="$t('table.enterThe')+'最低消费金额'" style="width:45%" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 分类选择 -->
    <el-dialog title="分类选择" :visible="showDialogC" width="50%" @close="btnCanleC">
      <el-table tooltip-effect="dark" border :data="cateList" max-height="650px" style="margin-top: 20px;" :tree-props="{children: 'children'}" row-key="id">
        <el-table-column label="ID" prop="id" sortable="custom" width="60" />
        <el-table-column :label="$t('table.commodity_information')" prop="name" />
        <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button :disabled="row.pid===0" icon="el-icon-edit" type="primary" size="mini" @click="selectC(row)">{{ $t('button.select') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 商品选择 -->
    <el-dialog title="商品选择" :visible="showDialogS" width="50%" @close="btnCanleS">
      <!-- 搜索筛选 -->
      <el-row :gutter="20" style="margin-top:20px">
        <el-col :span="6">
          <el-input v-model="queryS.name" type="text" :placeholder="$t('table.productName')" />
        </el-col>
        <el-col :span="6">
          <el-select v-model.number="queryS.cid" :placeholder="$t('table.selectThe')+$t('route.productCate')" style="width: 100%;" clearable @clear="clearCate">
            <el-option-group v-for="(item,index) in cateList" :key="index" :label="item.name" :value="item.id">
              <el-option v-for="(item1,index1) in item.children" :key="index1" :label="item1.name" :value="item1.id" />
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" icon="el-icon-search" @click="searchS">{{ $t('button.search') }}</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="downloadLoadingS" tooltip-effect="dark" border :data="listS" max-height="650px" style="margin-top: 20px;">
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" prop="shop_product.id" sortable="custom" width="60" />
        <el-table-column :label="$t('table.commodity_information')" prop="shop_goods" width="300">
          <template slot-scope="{row}">
            <div class="shopGoods-item">
              <div class="shopGoos_img"><img :src="row.shop_product.pic" width="100%"></div>
              <div class="shopGoos_wen">
                <p>{{ row.shop_product.name }}</p>
                <p class="goodsPrice">¥ {{ row.shop_product.sell_price }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.stock')" prop="shop_product.stock" />
        <el-table-column prop="shop_product.sales" :label="$t('table.sales')" />
        <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button icon="el-icon-edit" type="primary" size="mini" @click="selectS(row)">{{ $t('button.select') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" align="middle" style="margin-top:20px">
        <el-pagination background layout="total,prev,pager,next" :total="countS" :page-size="queryS.limit" :current-page="queryS.page" @current-change="changPageS" />
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { CouponList, CouponAdd, CouponDel, GetFuwuProduct, getLevelList, getShopCateList } from '@/api/user'
import user from '@/store/modules/user'
import { tranListTotreeDatCate, ArrNumne } from '@/utils'
export default ({
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: [],
      listS: [],
      downloadLoading: false,
      statusData: [{
        id: 1,
        value: this.$t('table.normal')
      },
      {
        id: 2,
        value: this.$t('table.deactivate')
      }],
      groupType: [{
        id: 1,
        value: '服务商品'
      },
      {
        id: 2,
        value: '实物商品'
      }],
      query: {
        id: undefined,
        name: '',
        sub_name: '',
        aid: 1,
        page: 1,
        type: undefined,
        limit: 10
      },
      queryS: {
        name: '',
        aid: 1,
        cid: undefined,
        status: 1,
        limit: 10,
        page: 1
      },
      count: 0,
      dialogTitle: this.$t('button.add'),
      formData: {
        aid: 1,
        id: undefined,
        name: '',
        yxqtype: 2,
        yxqdate: undefined,
        status: undefined,
        yxqstart_time: undefined,
        yxqend_time: undefined,
        money: undefined,
        minprice: undefined,
        stock: undefined,
        type: 1,
        perlimit: undefined,
        usetips: '',
        tolist: 0,
        price: undefined,
        score: undefined,
        showtj: '',
        gettj: '',
        fwtype: 0,
        categoryids: '',
        yuyue_productids: '',
        isgive: 0
      },
      rules: {
        name: [{ required: true, message: this.$t('table.name') + this.$t('prompt.noEmpty'), trigger: 'blur' }],
        status: [{ required: true, message: this.$t('table.state') + this.$t('prompt.noEmpty'), trigger: 'blur' }]
      },
      showDialog: false,
      checkList: [-1],
      listLevel: [],
      gettjList: [-1],
      cateList: [],
      cateListObj: [],
      showDialogC: false,
      shopList: [],
      showDialogS: false,
      downloadLoadingS: false,
      countS: 0
    }
  },
  created() {
    // 获取userid
    this.getBusinessCateList()
    this.getLevel()
  },
  methods: {
    // 获取商品列表
    async getProductListS() {
      this.downloadLoadingS = true
      const { count, list } = await GetFuwuProduct(this.queryS)
      this.countS = count
      // 给数组对象使用map循环添加新属性
      this.listS = list
      this.downloadLoadingS = false
    },
    // 获取分类列表
    async getShopCate() {
      const query = {
        id: undefined,
        bid: parseFloat(user.state.userInfo.bid),
        type: 1,
        aid: 1,
        page: 1,
        limit: 1000
      }
      const { list } = await getShopCateList(query)
      // 调用自定义的树状数组函数，处理获取的数组
      this.cateList = tranListTotreeDatCate(list, 0)
    },
    // 获取商户分了列表
    async getBusinessCateList() {
      this.downloadLoading = true
      const { count, list } = await CouponList(this.query)
      this.count = count
      this.list = list
      this.downloadLoading = false
    },
    // 获取等级
    async getLevel() {
      const query = {
        id: undefined,
        sub_name: '',
        name: '',
        aid: 1,
        page: 1,
        limit: 1000
      }
      const { list } = await getLevelList(query)
      this.listLevel = list
    },
    // 点击展开新增修改
    addOrEidt(type, row) {
      if (type === 'add') {
        this.dialogTitle = this.$t('button.add')
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        this.dialogTitle = this.$t('button.edit')
        this.formData.id = row.id
        this.formData.name = row.name
        this.formData.status = row.status
        this.formData.yxqtype = row.yxqtype
        this.formData.yxqdate = row.yxqdate
        this.formData.yxqstart_time = row.yxqstart_time * 1000
        this.formData.yxqend_time = row.yxqend_time * 1000
        this.formData.money = row.money
        this.formData.minprice = row.minprice
        this.formData.type = row.type
        this.formData.stock = row.stock
        this.formData.perlimit = row.perlimit
        this.formData.usetips = row.usetips
        this.formData.tolist = row.tolist
        this.formData.price = row.price
        this.formData.score = row.score
        this.formData.showtj = row.showtj
        this.formData.gettj = row.gettj
        this.checkList = ArrNumne(row.showtj)
        this.gettjList = ArrNumne(row.gettj)
        console.log(this.checkList)
        this.formData.fwtype = row.fwtype
        this.formData.categoryids = row.categoryids
        this.formData.yuyue_productids = row.yuyue_productids
        if (row.categoryids !== null) {
          this.cateListObj = row.cate_list
        }
        if (row.yuyue_productids !== null) {
          this.shopList = row.fu_shop
        }
        this.formData.isgive = row.isgive
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    // 点击确定时
    async btnOk() {
      try {
        // 校验整个表单
        await this.$refs.ruleForm.validate()
        if (this.checkList.length > 0) {
          this.formData.showtj = this.checkList.toString(',')
        }
        if (this.checkList.length > 0) {
          this.formData.gettj = this.gettjList.toString(',')
        }
        // 格式化推荐商品id
        if (this.shopList !== null) {
          if (this.shopList.length > 0) {
            const ShopId = []
            this.shopList.forEach(item => {
              ShopId.push(item.id)
            })
            this.formData.categoryids = ShopId.toString(',')
          }
        }
        if (this.cateListObj !== null) {
          if (this.cateListObj.length > 0) {
            const CateId = []
            this.cateListObj.forEach(item => {
              CateId.push(item.id)
            })
            this.formData.categoryids = CateId.toString(',')
          }
        }
        // 调用新增接口
        await CouponAdd(this.formData)
        // 更新数据
        this.getBusinessCateList()
        this.btnCanle()
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 删除管理员
    async delData(e) {
      const data = {
        id: e
      }
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await CouponDel(data)
        this.getBusinessCateList()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 移除当前的物流模版
    removeFreightArr(type, index) {
      if (type === 'cate') {
        this.cateListObj.splice(index, 1)
      } else if (type === 'shop') {
        this.shopList.splice(index, 1)
      } else {
        this.fuwuList.splice(index, 1)
      }
    },
    // 打开关联项目选择
    openFreight(type) {
      if (type === 'cate') {
        this.showDialogC = true
        this.getShopCate()
      } else if (type === 'shop') {
        this.showDialogS = true
        this.getProductListS()
      } else {
        this.showDialogFuwu = true
        this.getList()
      }
    },
    // 取消重置原来的数据
    btnCanle() {
      this.formData = {
        aid: 1,
        id: undefined,
        name: '',
        yxqtype: 2,
        yxqdate: undefined,
        status: undefined,
        yxqstart_time: undefined,
        yxqend_time: undefined,
        money: undefined,
        minprice: undefined,
        stock: undefined,
        type: 1,
        perlimit: undefined,
        usetips: '',
        tolist: 0,
        price: undefined,
        score: undefined,
        showtj: '',
        gettj: '',
        fwtype: 0,
        categoryids: '',
        yuyue_productids: '',
        isgive: 0
      }
      this.checkList = [-1]
      this.gettjList = [-1]
      this.cateListObj = []
      this.shopList = []
      this.$refs.ruleForm.clearValidate()// 重置校验结果
      this.showDialog = false
    },
    // 取消推荐商品
    btnCanleS() {
      this.showDialogS = false
    },
    // 搜索
    searchS() {
      this.queryS.page = 1
      this.getProductListS()
    },
    // 选择商品
    selectC(row) {
      this.cateListObj.push(row)
      this.showDialogC = false
    },
    // 选择商品
    selectS(row) {
      this.shopList.push(row.shop_product)
      this.showDialogS = false
    },
    // 取消关联项目选择
    btnCanleC() {
      this.showDialogC = false
    },
    // 分页
    changPageS(newPage) {
      this.queryS.page = newPage
      this.getProductListS()
    },
    // 搜索
    search() {
      this.query.page = 1
      this.getBusinessCateList()
    },
    // 分页
    changPage(newPage) {
      this.query.page = newPage
      this.getBusinessCateList()
    },
    clearCate() {
      this.query.cid = undefined
    },
    openDialog() {
      // 判断有icon的数据
      if (this.formData.pic) {
        // 这里我们赋值，同时需要给赋值的地址一个标记 upload: true
        this.$refs.staffPhoto.fileList = [{ url: this.formData.pic, upload: true }]
      }
    }
  }
})
</script>
<style lang="scss">
.table-img{
  width: 90px;
}
.margin-left-10{
  margin-left: 10px;
}
.shopOrder-dialog{
  height: auto;
  max-height: 650px;
  overflow-y: auto;
}
.shopOrder-dialog::-webkit-scrollbar{display:none}
.ljm-table{
  thead{
    tr{
      background-color: #f2f2f2;
      th{
        border-width: 1px;
        border-style: solid;
        border-color: #e6e6e6;
        position: relative;
        padding: 9px 15px;
        min-height: 20px;
        line-height: 20px;
        font-size: 14px;
        text-align: left;
      }
    }
  }
  tbody{
    tr{
      margin-top: -1px;
      td{
        position: relative;
        padding: 9px 15px;
        min-height: 20px;
        line-height: 20px;
        font-size: 14px;
        border-width: 1px;
        border-style: solid;
        border-color: #e6e6e6;
        .layui-input{
          display: inline;
          height: 30px;
          padding-left: 10px;
          line-height: 1.3;
          border-width: 1px;
          border-style: solid;
          background-color: #fff;
          border-radius: 2px;
          border-color: #e6e6e6;
        }
        .guanlian{
          display: flex;
          align-items: center;
        }
        div{
          margin: 5px 0px;
          .layui-btn-sm{
            height: 30px;
            line-height: 30px;
            padding: 0 10px;
            font-size: 12px;
            margin-left: 5px;
          }
          .layui-btn-primary{
            border: 1px solid #C9C9C9;
            background-color: #fff;
            color: #555;
          }
          .layui-btn {
              display: inline-block;
              white-space: nowrap;
              text-align: center;
              border-radius: 2px;
              cursor: pointer;
          }
        }
      }
    }
  }
}
.shopGoods-item{
  display: flex;
  margin-bottom: 15px;
  .shopGoos_img{
    width: 80px;
    margin-right: 10px;
  }
  .shopGoos_wen{
    width: 200px;
    font-size: 12px;
    line-height: 18px;
    p{
      margin: 0;
    }
  }
  .goodsPrice{
    color: #f60;
    margin-top: 20px;
  }
}
</style>
